package com.kukudexin.freemark.test;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: skyline{http://my.oschina.net/skyline520}
 * Date: 13-1-9
 * Time: 下午2:23
 * To change this template use File | Settings | File Templates.
 */
public class GenerateRule {
    public void generateMain() throws IOException, TemplateException {
        /* 在整个应用的生命周期中，这个工作你应该只做一次。 */
        /* 创建和调整配置。 */
        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("myTemplate", "rule\n" +
                "<#if action??>\n" +
                " ${action}\n" +
                "</#if>\n" +
                "<#if protocol??>\n" +
                " ${protocol}\n" +
                "</#if>\n" +
                "<#if source_ip_address??>\n" +
                "\t<#if source_wildcard??>\n" +
                " source ${source_ip_address} ${source_wildcard}\n" +
                "\t</#if>\n" +
                "</#if>\n" +
                "<#if destination_ip_address??>\n" +
                "\t<#if destination_wildcard??>\n" +
                " destination ${destination_ip_address} ${destination_wildcard}\n" +
                "\t</#if>\n" +
                "</#if>\n" +
                "<#if operator??>\n" +
                "\t<#if destination_port??>\n" +
                " destination_port ${operator} ${destination_port}\n" +
                "\t</#if>\n" +
                "</#if>");
        cfg.setTemplateLoader(stringLoader);
        Template temp = cfg.getTemplate("myTemplate","utf-8");
        /* 创建数据模型 */
        Map root = new HashMap();
        root.put("action"  ,"deny"  );
        root.put("protocol" ,"udp"  );
        root.put("source_ip_address"  ,"192.168.56.123"  );
        root.put("source_wildcard"  ,"0.0.0.255"  );
        root.put("destination_ip_address"  ,"192.168.56.123"  );
        root.put("destination_wildcard"  ,"0.0.0.255"  );
        root.put("operator"  ,"gt"  );
        root.put("destination_port"  ,"128"  );
        Writer out = new StringWriter(2048);
        temp.process(root, out);
        System.out.println(out.toString().replaceAll("[\\n\\r]", ""));
        out.flush();
    }

    public static void main(String[] args) throws Exception {
        GenerateRule html = new GenerateRule();
        html.generateMain();
    }
}
